<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      label-width="68px"
      :class="{'mobile-form': isMobile}"
    >
      <el-form-item
        label="登录地址"
        prop="ipaddr"
      >
        <el-input
          v-model="queryParams.addr"
          placeholder="请输入登录地址"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="用户名称"
        prop="userName"
      >
        <el-input
          v-model="queryParams.creator"
          placeholder="请输入用户名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>

    </el-form>
    
    <!-- 桌面端表格视图 -->
    <el-table
      v-loading="loading"
      :data="list"
      style="width: 100%;"
      v-if="!isMobile"
    >
      <el-table-column
        label="序号"
        type="index"
        align="center"
      >
        <template slot-scope="scope">
          <span>{{(queryParams.page - 1) * queryParams.page_size + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="会话编号"
        align="center"
        prop="id"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="登录名称"
        align="center"
        prop="creator"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="部门名称"
        align="center"
        prop="deptName"
      />
      <el-table-column
        label="主机"
        align="center"
        prop="ipaddr"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="登录地点"
        align="center"
        prop="loginLocation"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="浏览器"
        align="center"
        prop="browser"
      />
      <el-table-column
        label="操作系统"
        align="center"
        prop="os"
      />
      <el-table-column
        label="登录时间"
        align="center"
        prop="create_time"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleForceLogout(scope.row)"
            v-hasPermi="['monitor:online:forceLogout']"
          >强退</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 移动端卡片视图 -->
    <div class="mobile-card-view" v-if="isMobile">
      <div v-if="list.length === 0" class="empty-data">
        <i class="el-icon-document"></i>
        <p>暂无数据</p>
      </div>
      
      <el-card v-for="(item, index) in list" :key="index" class="mobile-card" shadow="hover">
        <div slot="header" class="card-header">
          <div class="user-title" :style="{ color: theme }">{{ item.creator || '未知用户' }}</div>
          <div class="login-info">
            <el-tag size="small" type="info">{{ item.ipaddr || '未知IP' }}</el-tag>
          </div>
        </div>
        <div class="card-content">
          <div class="user-info">
            <div class="info-item" v-if="item.deptName">
              <span class="label">部门：</span>
              <span class="value">{{ item.deptName }}</span>
            </div>
            <div class="info-item">
              <span class="label">登录时间：</span>
              <span class="value">{{ parseTime(item.create_time) }}</span>
            </div>
          </div>
          <div class="user-details" v-if="expandedCards[index]">
            <div class="details-section">
              <div class="info-item" v-if="item.browser">
                <span class="label">浏览器：</span>
                <span class="value">{{ item.browser }}</span>
              </div>
              <div class="info-item" v-if="item.os">
                <span class="label">操作系统：</span>
                <span class="value">{{ item.os }}</span>
              </div>
              <div class="info-item" v-if="item.loginLocation">
                <span class="label">登录地点：</span>
                <span class="value">{{ item.loginLocation }}</span>
              </div>
              <div class="info-item" v-if="item.id">
                <span class="label">会话ID：</span>
                <span class="value">{{ item.id }}</span>
              </div>
            </div>
          </div>
          <div class="card-actions">
            <el-button 
              type="danger" 
              size="small" 
              icon="el-icon-delete"
              @click="handleForceLogout(item)" 
              v-hasPermi="['monitor:online:forceLogout']">
              强制退出
            </el-button>
            <div class="card-toggle">
              <el-button type="text" size="small" @click="expandCard(index)">
                {{ expandedCards[index] ? '收起' : '查看详情' }}
                <i :class="expandedCards[index] ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i>
              </el-button>
            </div>
          </div>
        </div>
      </el-card>
      
      <!-- 移动端分页 -->
      <div class="mobile-pagination" v-if="total > 0">
        <div class="mobile-pagination-wrapper">
          <!-- 第一行：总数和每页条数 -->
          <div class="pagination-row top-row">
            <span class="el-pagination__total">共 {{ total }} 条</span>
            <el-select 
              v-model="queryParams.page_size" 
              size="mini" 
              class="el-pagination__sizes"
              @change="handleSizeChange">
              <el-option
                v-for="item in [10, 20, 30, 50]"
                :key="item"
                :label="`${item}条/页`"
                :value="item">
              </el-option>
            </el-select>
          </div>
          
          <!-- 第二行：页码导航 -->
          <div class="pagination-row bottom-row">
            <el-pagination
              background
              @current-change="handleCurrentChange"
              :current-page="queryParams.page"
              :page-size="queryParams.page_size"
              layout="prev, pager, next, jumper"
              :total="total">
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 桌面端分页 -->
    <pagination
      v-show="total > 0 && !isMobile"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.page_size"
      @pagination="getList"
    />

  </div>
</template>

<script>
import { list, forceLogout } from "@/api/vadmin/monitor/online";
import { mapState } from "vuex";

export default {
  name: "Online",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 表格数据
      list: [],

      // 查询参数
      queryParams: {
        ipaddr: undefined,
        userName: undefined,
        page: 1,
        page_size: 10,
      },
      
      // 移动端相关
      screenWidth: document.body.clientWidth,
      isMobile: false,
      expandedCards: [],
      mediaQueryList: null
    };
  },
  
  computed: {
    ...mapState(["settings"]),
    theme() {
      return this.$store.state.settings.theme;
    }
  },
  
  created() {
    this.getList();
    // 初始化移动设备状态
    this.isMobile = document.body.clientWidth < 768;
    // 监听屏幕宽度变化
    window.addEventListener('resize', this.handleResize);
  },
  
  mounted() {
    // 使用媒体查询API直接监听视口变化
    this.mediaQueryList = window.matchMedia('(max-width: 767px)');
    
    // 初始化isMobile状态
    this.isMobile = this.mediaQueryList.matches;
    
    // 为媒体查询添加监听器
    const handleMediaChange = (e) => {
      this.isMobile = e.matches;
      // 强制组件重新渲染
      this.$forceUpdate();
    };
    
    // 使用适当的API添加监听器
    if (this.mediaQueryList.addEventListener) {
      this.mediaQueryList.addEventListener('change', handleMediaChange);
    } else {
      // 旧版浏览器支持
      this.mediaQueryList.addListener(handleMediaChange);
    }
    
    // 存储监听器以便后续移除
    this.mediaChangeHandler = handleMediaChange;
  },
  
  beforeDestroy() {
    // 移除监听器
    window.removeEventListener('resize', this.handleResize);
    
    // 移除媒体查询监听器
    if (this.mediaQueryList) {
      if (this.mediaQueryList.removeEventListener) {
        this.mediaQueryList.removeEventListener('change', this.mediaChangeHandler);
      } else {
        // 旧版浏览器支持
        this.mediaQueryList.removeListener(this.mediaChangeHandler);
      }
    }
  },
  
  methods: {
    // 处理屏幕大小变化
    handleResize() {
      this.screenWidth = document.body.clientWidth;
      this.isMobile = this.screenWidth < 768;
    },
    
    // 卡片展开/收起
    expandCard(index) {
      this.$set(this.expandedCards, index, !this.expandedCards[index]);
    },
    
    // 分页处理
    handleSizeChange(size) {
      this.queryParams.page_size = size;
      this.getList();
    },
    
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    
    /** 查询登录日志列表 */
    getList() {
      this.loading = true;
      list(this.queryParams).then((response) => {
        this.list = response.results;
        this.total = response.count;
        this.loading = false;
        // 初始化展开卡片状态
        this.expandedCards = Array(this.list.length).fill(false);
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 强退按钮操作 */
    handleForceLogout(row) {
      this.$confirm('是否确认强退名称为"' + row.ipaddr + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return forceLogout(row.id);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("强退成功");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  background-color: transparent;
}

/* 移动端表单样式 */
.mobile-form {
  display: flex;
  flex-direction: column;
  margin-bottom: 15px;
  
  .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
    width: 100%;
    
    /deep/ .el-form-item__content {
      width: 100%;
      display: flex;
      
      .el-input,
      .el-select {
        flex: 1;
      }
      
      .el-button {
        margin-left: 0;
        margin-right: 10px;
        
        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}

/* 移动端卡片视图样式 */
.mobile-card-view {
  margin-top: 15px;
  
  .empty-data {
    text-align: center;
    padding: 40px 0;
    color: #909399;
    
    i {
      font-size: 40px;
      margin-bottom: 10px;
    }
    
    p {
      font-size: 14px;
    }
  }
  
  .mobile-card {
    margin-bottom: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
    transition: all 0.3s;
    
    &:active {
      transform: scale(0.99);
    }
    
    /deep/ .el-card__header {
      padding: 12px 15px;
      border-bottom: 1px solid #f0f0f0;
    }
    
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .user-title {
        font-weight: bold;
        font-size: 16px;
        line-height: 1.3;
        flex: 1;
      }
    }
    
    .card-content {
      padding: 10px 0;
      
      .user-info {
        margin: 10px 0;
        
        .info-item {
          margin: 8px 0;
          display: flex;
          flex-wrap: wrap;
          align-items: center;
          
          .label {
            color: #606266;
            margin-right: 5px;
            font-size: 14px;
          }
          
          .value {
            color: #333;
            font-size: 14px;
          }
        }
      }
      
      .user-details {
        margin-top: 15px;
        background-color: #f8f9fa;
        border-radius: 6px;
        padding: 10px 15px;
        
        .details-section {
          margin-bottom: 10px;
          
          &:last-child {
            margin-bottom: 0;
          }
        }
      }
      
      .card-actions {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-top: 15px;
        flex-wrap: wrap;
        
        .card-toggle {
          margin-top: 5px;
        }
      }
    }
  }
  
  /* 移动端分页样式 */
  .mobile-pagination {
    margin-top: 15px;
    
    .mobile-pagination-wrapper {
      background-color: #fff;
      border-radius: 8px;
      box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
      padding: 10px;
      
      .pagination-row {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 8px;
        flex-wrap: wrap;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        &.top-row {
          border-bottom: 1px solid #ebeef5;
          padding-bottom: 8px;
          justify-content: space-around;
        }
        
        &.bottom-row {
          padding-top: 5px;
        }
        
        .el-pagination__total {
          margin: 5px 5px 5px 0;
          font-size: 13px;
          color: #606266;
          font-weight: normal;
          white-space: nowrap;
        }
        
        .el-pagination__sizes {
          width: auto;
          margin: 5px 0;
          
          /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
            font-size: 13px;
            border-radius: 4px;
          }
        }
        
        /deep/ .el-pagination {
          padding: 0;
          white-space: normal;
          background: transparent;
          text-align: center;
          width: 100%;
          
          &.is-background {
            .btn-next,
            .btn-prev,
            .el-pager li {
              margin: 3px;
              min-width: 28px;
              height: 28px;
              line-height: 28px;
              font-size: 12px;
              font-weight: normal;
              background-color: #fff;
              border: 1px solid #dcdfe6;
              border-radius: 4px;
            }
            
            .el-pager li:not(.disabled).active {
              background-color: var(--theme);
              color: #fff;
              border-color: var(--theme);
            }
          }
          
          .el-pagination__jump {
            margin: 5px 0 5px 10px;
            font-size: 13px;
            color: #606266;
            display: flex;
            align-items: center;
            flex-wrap: nowrap;
            white-space: nowrap;
            
            /deep/ .el-input {
              width: 45px;
              margin: 0 3px;
              
              .el-input__inner {
                height: 28px;
                line-height: 28px;
                padding: 0 3px;
                text-align: center;
                font-size: 13px;
                border-radius: 4px;
              }
            }
          }
        }
      }
    }
  }
}

/* 超小屏幕特殊处理 */
@media screen and (max-width: 360px) {
  .mobile-pagination {
    .mobile-pagination-wrapper {
      padding: 8px 5px;
      
      .pagination-row {
        &.top-row {
          flex-direction: column;
          align-items: center;
          
          .el-pagination__total {
            margin-bottom: 8px;
          }
        }
      }
    }
  }
}
</style>

